function generateUUID() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
    });
    return UUID(uuid);
};

var gcL1Id;
var ir = db.CriteriaLevel1.findOne({ 'Name': 'Impact Radar' })
if (ir) {
    gcL1Id = ir._id;
    // change Impact Radar to Global Compact
    db.CriteriaLevel1.update({ _id: gcL1Id }, { $set: { 'Name': 'Global Compact', 'ShortName': 'Global Compact' } });
}
else {
    var gcL1 = db.CriteriaLevel1.findOne({ 'Name': 'Global Compact' });
    if (!gcL1) {
        gcL1Id = generateUUID();
        db.CriteriaLevel1.insert({
            "_id": gcL1Id,
            "Name": "Global Compact",
            "ShortName": "Global Compact"
        })
    }
    else {
        gcL1Id = gcL1._id;
        db.CriteriaLevel1.update({ _id: gcL1Id },
        {
            $set:
            {
                "Name": "Global Compact",
                "ShortName": "Global Compact"
            }
        })
    }
}

// Add GC Level 2
if (!db.CriteriaLevel2.findOne({ CriteriaLevel1Id: gcL1Id })) {
    var gcL2Id = generateUUID();
    db.CriteriaLevel2.insert({ _id: gcL2Id, CriteriaLevel1Id: gcL1Id, UniverseFeature: 12, Name: 'Global Compact Compliance', ShortName: 'Global Compact Compliance' })
}
else {
    db.CriteriaLevel2.update({ CriteriaLevel1Id: gcL1Id }, { $set: { UniverseFeature: 12, Name: 'Global Compact Compliance', ShortName: 'Global Compact Compliance' } })
}


// Add GC Template Criteria for GC Level 2 - GC Compliance
if (!db.TemplateCriteria.findOne({ CriteriaLevel2Id: gcL2Id })) {
    var gcTcGcComplianceId = generateUUID();
    db.TemplateCriteria.insert(
    {
        "_id": gcTcGcComplianceId,
        "Name": "Global Compact Compliance",
        "CriteriaEntity": "GCOverallCompanySummary",
        "CriteriaEntityField": "OverallCompanyAssessment",
        "BaseEventIndicatorId": null,
        "Score": null,
        "CriteriaLevel2Id": gcL2Id,
        "CriteriaType": 7,
        "FilterId": null,
        "CompaniesIdsResult": null
    });
}
else {
    db.TemplateCriteria.update({ CriteriaLevel2Id: gcL2Id },
    {
        $set:
        {
            "Name": "Global Compact Compliance",
            "CriteriaEntity": "GCOverallCompanySummary",
            "CriteriaEntityField": "OverallCompanyAssessment",
            "BaseEventIndicatorId": null,
            "Score": null,
            "CriteriaLevel2Id": gcL2Id,
            "CriteriaType": 7,
            "FilterId": null,
            "CompaniesIdsResult": null
        }
    });
}
